<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use \tpfcore\Core;
use think\Validate;

class UserAddress extends ApiBase
{
    public function getAddress($data = [])
    {
        $userinfo = $this->getBaseUserInfo();
        $user_id=$userinfo['id'];

        $where['user_id']=$user_id;

        if(isset($data['id'])) $where['id']=$data['id'];

        $result = self::getList(["where"=>$where]);
        return [0,"success",$result];
    }

    public function editAddress($data=[]){
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('opaddress')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }
        $userinfo = $this->getBaseUserInfo();
        $user_id=$userinfo['id'];
        $data['user_id']=$user_id;

        $result = self::saveObject($data);
        if($result){
            return [0,"success",$result];
        }
        return [40004,"操作失败"];
    }
    public function deleteAddress($data=[]){
        $userinfo = $this->getBaseUserInfo();
        $user_id=$userinfo['id'];
        $result = self::deleteObject(["id"=>$data['id'],"user_id"=>$user_id],true);
        if($result){
            return [0,"success"];
        }
        return [40004,"操作失败"];
    }
    public function setDefaultAddress($data=[]){
        $userinfo = $this->getBaseUserInfo();
        $user_id=$userinfo['id'];
        self::updateObject(["user_id"=>$user_id],["is_default"=>0]);

        $result = self::updateObject(["user_id"=>$user_id,"id"=>$data['id']],["is_default"=>1]);
        if($result)
            return [0,"success"];
        return [40004,"操作失败"];  
    }
}